<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          v-model="pageParams.keyword"
          style="margin-bottom: 10px"
          type="text"
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入员工姓名全员搜索"
          @input="changeValue"
        />
        <!-- 树形控件 -->
        <el-tree
          ref="deptTree"
          :data="depts"
          :props="defaultProps"
          default-expand-all
          :expand-on-click-node="false"
          highlight-current
          node-key="id"
          @current-change="selectNode"
        />
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button
            v-permission="'add-employee'"
            size="mini"
            type="primary"
            @click="$router.push('/employee/detail')"
          >添加员工</el-button>
          <el-button
            size="mini"
            @click="showExcelDialog = true"
          >excel导入</el-button>
          <el-button size="mini" @click="exportEmployee">excel导出</el-button>
        </el-row>
        <!-- 员工表格 -->
        <el-table :data="list">
          <el-table-column prop="staffPhoto" align="center" label="头像">
            <template v-slot="{ row }">
              <el-avatar
                v-if="row.staffPhoto"
                :src="row.staffPhoto"
                :size="30"
              />
              <span v-else class="username">{{ row.username?.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="mobile" label="手机号" sortable />
          <el-table-column prop="workNumber" label="工号" sortable />
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template v-slot="{ row }">
              <span v-if="row.formOfEmployment === 1">正式</span>
              <span v-else-if="row.formOfEmployment === 2">非正式</span>
              <span v-else>无</span>
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable />
          <el-table-column label="操作" width="280px">
            <template v-slot="{ row }">
              <el-button
                size="mini"
                type="text"
                @click="$router.push(`/employee/detail/${row.id}`)"
              >查看</el-button>
              <el-button size="mini" type="text" @click="btnRole(row.id)">角色</el-button>
              <el-button
                size="mini"
                type="text"
                @click="deleteRole(row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row style="height: 60px" align="middle" type="flex" justify="end">
          <el-pagination
            layout="total,prev, pager, next"
            :total="total"
            :current-page="pageParams.page"
            :page-size="pageParams.pagesize"
            @current-change="changePage"
          />
        </el-row>
        <!-- 导入excel文件 组件 -->
        <import-excel
          :show-excel-dialog.sync="showExcelDialog"
          @uploadSuccess="getEmployeeList"
        />
        <!-- 分配角色弹层dialog -->
        <el-dialog :visible.sync="showRoleDialog" title="分配角色">
          <el-checkbox-group v-model="roleIds">
            <el-checkbox
              v-for="item in roleList"
              :key="item.id"
              :label="item.id"
            >
              {{ item.name }}
            </el-checkbox>
          </el-checkbox-group>
          <el-row slot="footer" type="flex" justify="center">
            <el-col :span="6">
              <el-button type="primary" size="mini" @click="btnRoleOK">确定</el-button>
              <el-button size="mini" @click="showRoleDialog = false">取消</el-button>
            </el-col>
          </el-row>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script>
import { dataConvertion } from '@/utils'
import { getDepartment } from '@/api/department'
import {
  getEmployeeLists,
  exportEmployeeExcel,
  delEmployee,
  getEnableRoleList,
  getEmployeeDetail,
  assignRole
} from '@/api/employee'
import ImportExcel from './components/import-excel.vue'
import FileSaver from 'file-saver'

export default {
  name: 'Employee',
  components: { ImportExcel },
  data() {
    return {
      showExcelDialog: false, // 控制excel的弹层显示和隐藏
      depts: [], // 组织数据
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      // 存储员工列表
      list: [],
      // 存储员工列表的分页状态
      pageParams: {
        departmentId: null, // 树组件的节点
        page: 1, // 当前页码
        pagesize: 10, // 每页10条
        keyword: '' // 模糊搜索关键字
      },
      total: 0, // 记录员工的总数
      timer: null, // 定时器
      showRoleDialog: false, // 用来控制角色弹层的显示
      roleList: [], // 接收角色列表
      roleIds: [], // 用来双向绑定数据的
      currentUserId: null // 用来记录当前点击的用户id
    }
  },
  created() {
    this.getDepartment()
  },
  methods: {
    // 获取部门信息
    async getDepartment() {
      const result = await getDepartment()
      this.depts = dataConvertion(result, 0) // 递归方法 将列表转化成树形
      this.pageParams.departmentId = this.depts[0].id // 记录节点
      this.$nextTick(() => {
        // 设置默认选中的节点
        this.$refs.deptTree.setCurrentKey(this.pageParams.departmentId) // 通过 key 设置某个节点的当前选中状态，使用此方法必须设置 node-key 属性
      })
      this.getEmployeeList()
    },
    // 获取员工列表
    async getEmployeeList() {
      const { rows, total } = await getEmployeeLists(this.pageParams)
      this.list = rows
      this.total = total
    },
    // 监听树形节点被点击
    selectNode(node) {
      this.pageParams.departmentId = node.id
      this.pageParams.page = 1 // 设置第一页
      this.getEmployeeList() // 重新调用获取员工列表的方法
    },
    // 切换页码
    changePage(newPage) {
      this.pageParams.page = newPage // 赋值新页码
      this.getEmployeeList() // 查询数据
    },
    changeValue() {
      // 单位时间内只执行最后一次
      // this的实例上赋值了一个timer的属性
      clearTimeout(this.timer) // 清理上一次的定时器
      this.timer = setTimeout(() => {
        this.pageParams.page = 1
        this.getEmployeeList()
      }, 300)
    },
    // 导出文件excel
    async exportEmployee() {
      const res = await exportEmployeeExcel()
      FileSaver.saveAs(res, '员工列表.xlsx')
    },
    // 删除角色
    deleteRole(id) {
      this.$confirm('确定删除该角色吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await delEmployee(id)
        this.$message.success('删除成功')
        this.getRoleList()
      })
    },
    // 点击角色按钮 弹出层
    async btnRole(id) {
      this.roleList = await getEnableRoleList()
      // 记录当前点击的id 因为后边 确定取消要存取给对应的用户
      this.currentUserId = id
      const { roleIds } = await getEmployeeDetail(id)
      this.roleIds = roleIds
      this.showRoleDialog = true // 调整顺序
    },
    // 点击角色的确定
    async  btnRoleOK() {
      await assignRole({
        id: this.currentUserId,
        roleIds: this.roleIds
      })
      this.$message.success('分配用户角色成功')
      this.showRoleDialog = false
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin: 10px;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04c9be;
      font-size: 12px;
      display: inline-block;
    }
  }
}
</style>
